﻿/*
 * Autore: Paolo Farina
 */

using System;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using RecipesManager.Data;

namespace RecipesManager.MainControls.ShopListSubControls
{
    public class ShopElems
    {
        public ShopElems(string name, ShopRating rate)
        {
            Name = name;
            if (rate.Equals(ShopRating.Good)) Rate = "Buono";
            else Rate = "";
            
        }

        public string Name { get; set; }
        public string Rate { get; set; }

        // override object.Equals
        public override bool Equals(object obj)
        {
            if (obj == null || GetType() != obj.GetType())
            {
                return false;
            }
            return ((ShopElems)obj).Name.Equals(this.Name) && ((ShopElems)obj).Rate == this.Rate;
        }

        public override int GetHashCode()
        {
            return base.GetHashCode();
        }
    }

    /// <summary>
    /// Logica di interazione per ShopListMainPane.xaml
    /// </summary>
    public partial class ShopListMainPane : UserControl
    {
        public IIngredientQuantity _ingredient = null;
        bool _editing = false;
        const MeasureFamily CurrentMeasureFamily = MeasureFamily.Metric;
        ObservableCollection<ShopElems> shopElems;
 

        public ShopListMainPane(string name, string udm)
        {
            InitializeComponent();
            if (name != null && !name.Equals(""))
            {
                var ingr = Manager.ShoppingList[name, udm];
                _ingredient = ingr;
                tb_title.Text = _ingredient.Name;
                _editing = true;
                tb_quantity.Text = _ingredient.Quantity+"";
                cb_ingredients.Visibility = Visibility.Collapsed;
                lb_nomeIngr.Visibility = Visibility.Collapsed;
                cb_measures.IsEditable = true;
                cb_measures.Text = _ingredient.Measure.Name;
                cb_measures.IsEnabled = false;
                bt_salva.IsEnabled = false;
                shopElems = new ObservableCollection<ShopElems>();
                foreach (var rating in Data.Manager.Ingredients[ingr.Name].ShopRatings)shopElems.Add(new ShopElems(rating.Name, rating.Rating));
                dg_shops.ItemsSource = shopElems;
            }
            else
            {
                tb_title.Text = "Nuovo Ingrediente";
                foreach (var ingredient in Manager.Ingredients) cb_ingredients.Items.Add(ingredient.Name);
                bt_salva.IsEnabled = false;
            }


        }

        void UpdateShopList(string ingredientName = "")
        {
            if (ingredientName.Equals(""))
            {
                shopElems.Clear();
                return;
            }

            var ingr = Manager.Ingredients[ingredientName];
            shopElems = new ObservableCollection<ShopElems>();
            foreach (var rating in Data.Manager.Ingredients[ingr.Name].ShopRatings) shopElems.Add(new ShopElems(rating.Name, rating.Rating));
            dg_shops.ItemsSource = shopElems;
        }

        public bool Save()
        {
            try
            {
                IIngredientQuantity iq = null;

                double quantityNumber = 0;
                
                if (!Double.TryParse(tb_quantity.Text, out quantityNumber))
                    throw new Exception("Si assicuri che la quantità sia un numero valido.");
                if (quantityNumber <= 0)
                    throw new Exception("Si assicuri che la quantità sia un numero maggiore di 0.");

                if (_editing)
                {
                    iq = Manager.ShoppingList[_ingredient.Name, _ingredient.Measure.Name];
                    iq.Update(iq.Measure.Name, quantityNumber, "");
                }
                else
                {
                    if (cb_measures.SelectedItem == null)
                        throw new Exception("Si assicuri di aver selezionato una unità di misura.");

                    _ingredient=Manager.ShoppingList.Add((string)cb_ingredients.SelectedValue, (string)cb_measures.SelectedValue , quantityNumber);
                    cb_ingredients.IsEnabled = false;
                    tb_title.Text = cb_ingredients.SelectedValue as string;
                    cb_ingredients.Visibility=Visibility.Collapsed;
                    lb_nomeIngr.Visibility=Visibility.Collapsed;
                    cb_measures.IsEnabled = false;
                    cb_measures.SelectedValue = _ingredient.Measure.Name;
                    tb_quantity.Text = _ingredient.Quantity + "";
                    _editing = true;

                }

                bt_salva.IsEnabled = false;


               
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message, "Avviso", MessageBoxButton.OK,
                                MessageBoxImage.Error);
                return false;
            }

            return true;
        }

        void UpdateQuantityCombobox(string ingredientName = "")
        {
            if (ingredientName.Equals(""))
            {
                cb_measures.Items.Clear();
                return;
            }

            cb_measures.Items.Clear();
            var currentMeasureType = Manager.Ingredients[ingredientName].MeasureType;
            var currentMeasures = Data.Operations.Operations.GetOrderedMeasures(CurrentMeasureFamily, currentMeasureType);
            foreach (var m in currentMeasures)
                cb_measures.Items.Add(m.Name);
        }

        private void Cb_Ingredients_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var comboBox = sender as ComboBox;
            if (comboBox == null) return;

            var selectedIngredient = cb_ingredients.SelectedItem as string;
            if (selectedIngredient == null)
                return;

            UpdateQuantityCombobox(selectedIngredient);
            UpdateShopList(selectedIngredient);
            tb_quantity.Focus();
            bt_salva.IsEnabled = IsModified();
           
        }

        public bool IsModified()
        {
            if (_ingredient == null)
                if (cb_ingredients.SelectedIndex != -1 || cb_measures.SelectedIndex != -1 ||
                 !tb_quantity.Text.Equals(""))
                    return true;
                else
                    return false;

            var selectedMeasure = cb_measures.SelectedItem as string;
            if (selectedMeasure == null)
                return true;

            return !selectedMeasure.Equals(_ingredient.Measure) ||
                   !tb_quantity.Text.Equals(_ingredient.Quantity.ToString(CultureInfo.InvariantCulture));

        }


        private void Cb_Measures_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            
            if(Manager.Ingredients.Contains(cb_ingredients.SelectedValue))
            {
                bt_salva.IsEnabled = IsModified();
                
            }
        }

        private void Dg_Shops_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            string message = "";
            var shop = Data.Manager.Shops[((ShopElems) dg_shops.SelectedValue).Name];
            message = shop.Name + "\n" + shop.PhoneNumber + "\n" + shop.Address + "\n" + shop.City + "\n" +
                      shop.Timetable + "\n";
            MessageBox.Show(message, "InfoNegozio", MessageBoxButton.OK,
                                MessageBoxImage.Information);
        }

        private void Tb_Quantity_TextChanged(object sender, TextChangedEventArgs e)
        {
            bt_salva.IsEnabled = IsModified();
        }
    }
}
